package com.whately.core.base.fileupload.qiniu.conf;

import com.whately.core.base.fileupload.constant.FileModeEnum;
import com.whately.core.base.fileupload.qiniu.model.QiNiuBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
@Slf4j
public class QiNiuFileServerInfo {

    /**************************************************************
     *    图片获取 ：配置七牛云的domain
     *************************************************************/

    @Autowired
    private QiNiuBean qiNiuBean;

    @Autowired
    private QiNiuSelfDefineConfigUploadFile selfDefineConfigUploadFile;


    // 当前域名列表
    private Map<String, String[]> DOMAIN_LIST;


    @PostConstruct
    public void init(){
        DOMAIN_LIST = new HashMap<>();
        DOMAIN_LIST.put(FileModeEnum.img_opened.getMode(), qiNiuBean.getImgOpenedUrls().split(","));

        //私有空间
        DOMAIN_LIST.put(FileModeEnum.img_private.getMode(), qiNiuBean.getImgPrivateUrls().split(","));
    }


    /**
     * 场景：数据库存储是图片相对路径，前台需要图片绝对路径 获取图片绝对路径
     *
     * @param fileNameWithBucket
     *            图片的相对地址 corpCert/2016/03/07/13/01f0024f3dc6f0885f370281a2b41c8bfb.png
     * @param bucket
     *            bucket, 由ImageConstant中定义
     *
     */
    public  String qiNiuImageAbsoluteUrlDomain(String fileNameWithBucket, String bucket) {
        if (StringUtils.isEmpty(fileNameWithBucket)|| StringUtils.isBlank(bucket)) {
            log.warn("fileNameWithBucket is empty, file:{}, bucket:{}.", fileNameWithBucket, bucket);
            return "";
        }
        //去掉bucket
        String fileName = fileNameWithBucket.substring(bucket.length());
        if (StringUtils.isEmpty(fileName)) {
            log.warn("fileName is empty, file:{}, bucket:{}.", fileName, bucket);
            return "";
        }
        // 兼容旧版本绝对URL地址
        if (fileName.trim().toLowerCase().startsWith("http://")) {
            // 旧版本url中可能会带参数,直接去掉
            if (-1 != fileName.indexOf('?')) {
                // 去掉后面的参数后返回
                return fileName.substring(0, fileName.indexOf('?'));
            } else {
                return fileName;
            }
        }

        if (fileName.length() <= 17) {   // 不合法的脏数据，直接返回空
            return "";
        }

        String fileMode ;
        try {
            fileName = fileName.substring(1);//  去掉/
            fileName = fileName.substring(fileName.indexOf("/"));  //去掉dev  profile
            fileName = fileName.substring(1);//  去掉/
            fileName = fileName.substring(fileName.indexOf("/"));  //去掉00   ds code
            fileMode = fileName.substring(15, 17);
            if (DOMAIN_LIST.get(fileMode) == null) {
                log.warn("getImageAbsoluteUrl by fileName[{}] bucket[{}] fail.", fileName, bucket);
                return "";
            }
        } catch (Exception e) {
            log.warn("getImageAbsoluteUrl exception:", e);
            return fileName;
        }

        // 随机从两个域名中获取
        String[] domains = DOMAIN_LIST.get(fileMode);

        int domainMode = 0;
        if(domains.length>1){
            new Random().nextInt(domains.length);
        }
        String protocol ;
        if(selfDefineConfigUploadFile.isHttpsOpenForQiNiu()){
            protocol = "https";
        }else{
            protocol = "http";
        }

        return  protocol+"://" + domains[domainMode] + "/" ;
    }

    /**************************************************************
     *    end of  图片获取 ： 从本地或者从七牛
     *************************************************************/


}
